package com.example.design.pattern.behavior

import kotlinx.coroutines.*


/**
 *Create by Fanketly on 2022/9/1
 *Gitee:https://gitee.com/fanketly
 *desc:目的：对象依赖一个状态，对象可以根据状态改变自己的行为
优点：状态转换与逻辑合在一起，而不是通过if语句隔开
缺点：会使结构比较复杂，也会增加类的个数
 */

fun main() {
    val mediaPlayer = MediaPlayer()
    mediaPlayer.start()
    while (!mediaPlayer.isOver)
        mediaPlayer.stop()
}

class MediaPlayer : Action {
    val startAction = StartAction(this)
    val stopAction = StopAction(this)
    var action: Action = startAction
    var isOver = false

    override fun start() {
        action.start()
    }

    override fun playing() {
        action.playing()
    }

    override fun stop() {
        action.stop()
    }
}

interface Action {
    fun start()
    fun playing()
    fun stop()
}

class StartAction(private val mediaPlayer: MediaPlayer) : Action {

    override fun start() {
        mediaPlayer.isOver = false
        println("start")
        playing()
    }

    override fun playing() {
        runBlocking {
            repeat(10) {
                delay(10)
                println("playing$it")
                if (!mediaPlayer.isOver && it == 9) {
                    println("over")
                    stop()
                }
            }
        }

    }

    override fun stop() {
        mediaPlayer.action = mediaPlayer.stopAction
    }

}

class StopAction(private val mediaPlayer: MediaPlayer) : Action {


    override fun start() {
        mediaPlayer.action = mediaPlayer.startAction
    }

    override fun playing() {
        println("stop")
    }

    override fun stop() {
        mediaPlayer.isOver = true
        println("stop")
    }
}